//
//  HeaderCountViewController.m
//  Quick_News
//
//  Created by 曾凯峻 on 15/1/30.
//  Copyright (c) 2015年 zkj. All rights reserved.
//

#import "HeaderCountViewController.h"
#import "MJRefresh.h"
@interface HeaderCountViewController ()

@end

@implementation HeaderCountViewController
//内存
- (void)dealloc
{
    [self.tableArr release];
    [self.tableView release];
    [self.CountDocid release];
    [self.progress release];
    [self.board release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableArr = [NSMutableArray array];
    
    
    //  设置导航栏左边返回按钮
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStyleDone target:self action:@selector(barButtonAction:)]autorelease];
    
   // self.navigationController.navigationBar.translucent = NO;
  //  NSLog(@"%@", self.CountDocid);
    if (!self.tableArr) {
        self.progress = [[MBProgressHUD alloc] initWithView:self.view];
        self.progress.labelText = @"请稍后";
        [self.progress show:YES];
        [self.view addSubview:self.progress];
        [self.progress release];
        [self creatView];
        [self creatData];
    } else {
        [self creatView];
        [self creatData];
    }
    
    
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.page = 10;
    }
    return self;
}

- (void)barButtonAction:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)creatData
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
   
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在刷新中,请稍后";
    
    self.tableView.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在加载中,不客气";
    

}


//加载方法
- (void)headerRereshing
{
    
    
    //自动刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableView reloadData];
        NSString *str = [NSString stringWithFormat:@"http://comment.api.163.com/api/json/post/list/new/normal/%@/%@/desc/0/10/10/2/2",self.board, self.CountDocid];
//        NSLog(@"%@", str);
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        __block HeaderCountViewController *CountVC = self;
        
        
        [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSMutableArray *tempArr = [responseObject objectForKey:@"newPosts"];
            for (NSDictionary *dic in tempArr) {
                NSDictionary *dic1 = [dic objectForKey:@"1"];
                //    NSLog(@"%@", dic1);
                TopNewsCount *count = [[TopNewsCount alloc] init];
                [count setValuesForKeysWithDictionary:dic1];
                [CountVC.tableArr addObject:count];
                [count release];
            }
            [self.tableView reloadData];
            [self.progress hide:YES];
//            [self creatView];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self.progress hide:YES];
            //警告
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起" message:@"网络加载出错啦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            NSLog(@"HeaderCountError:%@", error);
        }];
        
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
    
}


- (void)footerRereshing
{
    

         NSLog(@"%ld=========", self.page);

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            NSString *str = [NSString stringWithFormat:@"http://comment.api.163.com/api/json/post/list/new/normal/%@/%@/desc/%ld/10/10/2/2",self.board, self.CountDocid, self.page];
            self.page += 10;
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
            __block HeaderCountViewController *CountVC = self;
            
            
            [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSMutableArray *tempArr = [responseObject objectForKey:@"newPosts"];
                for (NSDictionary *dic in tempArr) {
                    NSDictionary *dic1 = [dic objectForKey:@"1"];
                    //    NSLog(@"%@", dic1);
                    TopNewsCount *count = [[TopNewsCount alloc] init];
                    [count setValuesForKeysWithDictionary:dic1];
                    
                    [CountVC.tableArr addObject:count];
                    [count release];
                }
                [self.tableView reloadData];
                [self.progress hide:YES];
                //            [self creatView];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self.progress hide:YES];
                //警告
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起" message:@"网络加载出错啦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
                [alertView release];
                NSLog(@"HeaderCountError:%@", error);
            }];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
            
        });
        
    
    
        
    
    
}


- (void)creatView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 70) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self.tableView release];
}
//cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArr.count;
}
//自定义cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"resue";
    CountCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:str];
    if (!cell) {
        cell = [[[CountCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    TopNewsCount *count = [self.tableArr objectAtIndex:indexPath.row];
    count.f = [count.f stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@"                                                                                                    "];
  // count.f = [count.f stringByReplacingOccurrencesOfString:@"网易" withString:@"                                                                                                    "];
    cell.nameLabel.text = count.f;
    cell.infoLabel.text = count.b;
    
    
    if (count.t == nil) {
        cell.timeLabel.text = @"    未知时间";
    } else {
    cell.timeLabel.text = count.t;
    }
//    NSLog(@"time:%@", count.t);
    return cell;
}
//一行cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopNewsCount *topNewsCount = [[TopNewsCount alloc] init];
    topNewsCount = [self.tableArr objectAtIndex:indexPath.row];
    NSString *str = topNewsCount.b;
    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:14.f]};
    
    CGRect rect = [str boundingRectWithSize:CGSizeMake(tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    

//    NSLog(@"rect:%f", rect.size.height);
    return rect.size.height + 60;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
